using System;
using System.Collections.Generic;

namespace Fusion.Utilities.Pools
{
    public class ObjectPool<T>
    {
        Func<T> factory;

        Queue<T> queue = new Queue<T>();
        HashSet<T> hashSet = new HashSet<T>();
        public event Action<T> OnGet;
        public event Action<T> OnRecycle;
        public ObjectPool(Func<T> factory)
        {
            this.factory = factory;
        }

        public T Get()
        {
            if (queue.Count == 0)
            {
                T result = factory();
                OnGet?.Invoke(result);
                return result;
            }
            T value = queue.Dequeue();
            hashSet.Remove(value);
            OnGet?.Invoke(value);
            return value;
        }

        public void Recycle(T data)
        {
            if (data == null || hashSet.Contains(data))
            {
                return;
            }
            OnRecycle?.Invoke(data);
            hashSet.Add(data);
            queue.Enqueue(data);
        }
    }
}